package com.xianggu.tomcat;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chengjy
 * @date 2025/3/6
 */
public class Response extends AbstractHttpServletResponse {
    private int status = 200;
    private String message = "OK";

    private Map<String, String> headers = new HashMap<>();

    private ResponseServletOutputStream responseServletOutputStream = new ResponseServletOutputStream();
    private Request request;
    private Socket socket;
    private OutputStream socketOutputStream;

    private static final byte[] CRLF = "\r\n".getBytes(StandardCharsets.UTF_8);
    private static final byte[] SP = " ".getBytes(StandardCharsets.UTF_8);

    public Response(Request request) {
        this.request = request;
        socket = request.getSocket();
        try {
            socketOutputStream = request.getSocket().getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void sendError(String message) throws IOException {
        this.status = 404;
        this.message = message;
        getOutputStream().write("找不到请求资源！".getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public int getStatus() {
        return getStatus();
    }

    @Override
    public void setStatus(int i, String message) {
        status = i;
        this.message = message;
    }

    @Override
    public void addHeader(String s, String s1) {
        headers.put(s, s1);
    }

    @Override
    public ResponseServletOutputStream getOutputStream() throws IOException {
        return responseServletOutputStream;
    }

    public void complete() {
        // 发送响应
        sendResponseLine();
        sendResponseHeader();
        sendResponseBody();
    }

    public void sendResponseBody() {
        try {
            String message = new String(getOutputStream().getBytes());
            socketOutputStream.write(message.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("发送响应体失败");
        }
    }

    /**
     * 响应头
     */
    private void sendResponseHeader() {
        if (!headers.containsKey("Content - Length")) {
            try {
                headers.put("Content - Length", String.valueOf(getOutputStream().index));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (!headers.containsKey("Content - Type")) {
            headers.put("Content - Type", "text/plain;charset=utf-8");
        }

        try {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String line = entry.getKey() + ": " + entry.getValue() + "\r\n";
                socketOutputStream.write(line.getBytes(StandardCharsets.UTF_8));
            }

            // 结束头部分
            socketOutputStream.write(CRLF);
        } catch (IOException e) {
            throw new RuntimeException("发送响应头失败2");
        }

    }

    /**
     * 响应行
     */
    private void sendResponseLine() {
        try {
            String responseLine = request.getProtocol() + " " + status + " " + message + "\r\n";
            socketOutputStream.write(responseLine.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException("发送响应行失败");
        }

    }

    @Override
    public String toString() {
        return super.toString();
    }
}
